#include "accespage.h"
#include "ui_accespage.h"

accespage::accespage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::accespage)
{
    ui->setupUi(this);
    ui->tableView_access->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView_access->setSelectionBehavior(QAbstractItemView::SelectRows);

    Query();
}

accespage::~accespage()
{
    delete ui;
}

void accespage::Query()
{
    int row = 0;
    ui->tableView_access->setRowCount(0);

    QSqlQuery query;
    if(query.exec("SELECT * FROM access"))
    {
        QSqlRecord record = query.record();
        ui->tableView_access->setColumnCount(record.count());
        ui->tableView_access->setHorizontalHeaderLabels({"车牌号","进入时间","出库时间","车位号","费用"});

        while(query.next())
        {
            ui->tableView_access->insertRow(row);
            for(int var = 0;var<record.count();++var)
            {
                ui->tableView_access->setItem(row,var,new QTableWidgetItem(query.value(var).toString()));
            }
            row++;
        }
    }
    else
    {
        qDebug() << "查询失败：" << query.lastError().text();
    }

}

void accespage::on_btn_refresh_clicked()
{
    Query();
}

void accespage::on_btn_search_clicked()
{
    while(ui->tableView_access->rowCount() > 0){
        ui->tableView_access->removeRow(0);
    }
    int row = 0;
    QSqlQuery query;
    query.prepare("SELECT * FROM access WHERE carid=:carId  OR stallid=:stallId");
    query.bindValue(":carId",ui->lineEdit->text());
    query.bindValue(":stallId",ui->lineEdit->text());

    if(query.exec())
    {
        QSqlRecord record = query.record();
        ui->tableView_access->setColumnCount(record.count());
        ui->tableView_access->setHorizontalHeaderLabels({"车牌号","    进入时间    ","    出库时间    ","车位号","费用"});

        while(query.next())
        {
            ui->tableView_access->insertRow(row);
            for(int var = 0;var<record.count();++var)
            {
                ui->tableView_access->setItem(row,var,new QTableWidgetItem(query.value(var).toString()));
            }
            row++;
        }
    }
    else
    {
        qDebug() << "查询失败：" << query.lastError().text();
    }

}

void accespage::on_btn_clear_clicked()
{
    // 清空模型中的所有行
    while (ui->tableView_access->rowCount() > 0) {
        ui->tableView_access->removeRow(0); // 从第一行开始，逐行移除
    }

}

void accespage::on_btn_del_clicked()
{
    QSqlQuery del;
    if(!del.exec("DELETE FROM access"))
        qDebug()<<"error:failed to DELETE FROM access";
    else
        qDebug()<<"Successfully DELETE FROM access";
    Query();

}
